package com.wtb.javatool.action;

import com.alibaba.fastjson.JSONPath;
import com.fy.wetoband.tool.Tool;
import com.fy.wetoband.utils.RequestUtil;
import com.wtb.javatool.common.R;
import com.wtb.javatool.common.ResultCode;
import com.wtb.javatool.constant.evaluation.AssetsType;
import com.wtb.javatool.entity.*;
import com.wtb.javatool.service.*;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Scope;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import static org.springframework.beans.factory.config.ConfigurableBeanFactory.SCOPE_PROTOTYPE;


@Api(value = "javatool")
@Scope(SCOPE_PROTOTYPE) //务必使用多实例模式
@ComponentScan("com.wtb.javatool")
public class VirtualClassroomToolAction extends Tool {

    @Autowired
    private CatalogService catalogService;

    @Autowired
    private AssetsService assetsService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    private CourseService courseService;

    @Resource
    private HomeworkService homeworkService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private TeamService teamService;

    /**
     * @param
     * @return : 获取当前帮区的目录数据
     */
    @Action
    public R getCatalogByBandId(HttpServletRequest request) {
        try {
            final Long schoolId = RequestUtil.getLongParameter(request, "schoolId");
            if (schoolId == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("学校id为空");
            }
            List<Catalog> catalogs = catalogService.getCatalogAndAssetsByBandId(getBandObjID(),schoolId);
            return R.ok().put("catalogs", catalogs).message("获取帮区目录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("获取帮区目录出错");
        }
    }


    /**
     * @param : id
     * @return : 根据目录id获取目录
     */
    @Action
    public R getCatalogById(HttpServletRequest request) {
        try {
            final Long id = Long.valueOf(RequestUtil.getStringParameter(request, "id"));
            if (id == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            Catalog catalog = catalogService.getById(id);
            if (catalog == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录不存在,请检查参数是否正确");
            }
            return R.ok().put("catalog", catalog).message("获取目录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("获取目录失败");
        }
    }


    /**
     * @param : level
     * @return : 根据目录level获取目录列表（目前用于获取目录模板（level=0））
     */
    @Action
    public R getCatalogByLevel(HttpServletRequest request) {
        try {
            final Integer level = RequestUtil.getIntegerParameter(request, "level");
            if (level == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            final List<Catalog> catalogs = catalogService.getByLevel(level);
            if (catalogs == null || catalogs.isEmpty()) {
                return R.error().code(ResultCode.ERROR.getCode()).message("暂无目录模板");
            }
            return R.ok().put("catalogs", catalogs).message("获取目录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("获取目录失败");
        }
    }


    /**
     * @param : 如下
     * @return : 创建目录
     */
    @Action
    public R createCatalog(HttpServletRequest request) {
        try {
            // 从请求中获取目录名称
            final String name = RequestUtil.getStringParameter(request, "name");
            // 从请求中获取目录级别
            final Integer level = RequestUtil.getIntegerParameter(request, "level");
            // 如果名称或级别为空，则返回错误信息
            if (name == null || level == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("参数不足");
            }
            // 从请求中获取目录排序顺序，如果未提供则默认为1
            Integer oldOrder = RequestUtil.getIntegerParameter(request, "order");
            final Integer order = oldOrder == null ? 1 : oldOrder;
            // 从请求中获取父目录ID
            final Long parentId = RequestUtil.getLongParameter(request, "parentId");
            // 从请求中获取学校ID
            final Long schoolId = RequestUtil.getLongParameter(request, "schoolId");

            // 创建一个新的目录对象并设置其属性
            Catalog catalog = new Catalog();
            catalog.setName(name);
            catalog.setLevel(level);
            catalog.setBandId(getBandObjID());
            catalog.setOrder(order);
            catalog.setParentId(parentId);
            catalog.setSchoolId(schoolId);

            // 调用catalogService的insert方法插入目录到数据库，并获取新目录的ID
            Long catalogId = catalogService.insert(catalog);
            if (catalogId > 0) {
                // 如果目录创建成功（即返回的ID大于0）返回新目录id
                return R.ok().message("创建目录成功").put("catalogId", catalogId);
            } else {
                // 如果创建失败，则返回错误信息
                return R.error().code(ResultCode.ERROR.getCode()).message("创建目录失败，请检数据库日志");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("创建目录失败，请检查系统日志");
        }
    }


    /**
     * @param : 改啥给啥
     * @return : 更新目录
     */
    @Action
    public R updateCatalog(HttpServletRequest request) {
        try {
            final Long id = RequestUtil.getLongParameter(request, "id");
            if (id == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            final String name = RequestUtil.getStringParameter(request, "name");
            final Integer level = RequestUtil.getIntegerParameter(request, "level");
            final Integer order = RequestUtil.getIntegerParameter(request, "order");
            final Long parentId = RequestUtil.getLongParameter(request, "parentId");

            Catalog catalog = new Catalog();
            catalog.setId(id);
            catalog.setName(name);
            catalog.setLevel(level);
            catalog.setBandId(getBandObjID());
            catalog.setOrder(order);
            catalog.setParentId(parentId);

            int updateCount = catalogService.update(catalog);
            if (updateCount > 0) {
                return R.ok().message("更新目录成功");
            } else {
                return R.error().code(ResultCode.ERROR.getCode()).message("更新目录失败，没有找到该数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("更新目录失败，请检查系统日志");
        }
    }


    /**
     * @param : id
     * @return : 根据目录id删除目录
     */
    @Action
    public R deleteCatalogById(HttpServletRequest request) {
        try {
            final Long id = RequestUtil.getLongParameter(request, "id");
            if (id == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            if (catalogService.getById(id) == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录不存在，无法删除");
            }
            catalogService.delete(id);
            return R.ok().message("删除目录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("删除目录失败，请检查系统日志");
        }
    }


    /**
     * @param : id列表
     * @return : 根据目录id列表批量删除目录
     */
    @Action
    public R deleteManyCatalogById(HttpServletRequest request) {
        try {
            List<Long> ids = RequestUtil.getLongJsonArrayParameterWithoutRepeat(request, "ids");
            if (CollectionUtils.isEmpty(ids)) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            assetsService.deleteManyByCatalogId(ids);
            catalogService.deleteMany(ids);
            return R.ok().message("删除目录成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("批量删除目录失败，请检查系统日志");
        }
    }


    /**
     * @param : id
     * @return : 根据目录id导入目录及其子目录
     */
    @Action
    public R cloneCatalogById(HttpServletRequest request) {
        try {
            Long catalogId = RequestUtil.getLongParameter(request, "id");
            if (catalogId == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            Boolean success = catalogService.cloneCatalog(catalogId, getBandObjID());
            if (success)
                return R.ok().message("目录导入成功");
            else
                return R.error().code(ResultCode.ERROR.getCode()).message("目录导入失败，请检数据库日志");
        } catch (Exception e) {
            // 处理异常，例如记录日志，并返回错误消息
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("目录导入失败，请检查系统日志");
        }
    }


    /**
     * 资源接口放下面
     */

    /*****************************************************************************************************************************************/

    /**
     * @param : id
     * @return : 根据资源id获取资源
     */
    @Action
    public R getAssetsById(HttpServletRequest request) {
        try {
            final Long id = Long.valueOf(RequestUtil.getStringParameter(request, "id"));
            if (id == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("资源id为空");
            }
            Assets assets = assetsService.getById(id);
            if (assets == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("资源不存在,请检查参数是否正确");
            }
            return R.ok().put("assets", assets).message("获取资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("获取资源失败");
        }
    }


    /**
     * 创建资源
     *
     * @param : 如下
     * @return :
     */
    @Action
    public R createAssets(HttpServletRequest request) {
        try {
            final Long documentId = RequestUtil.getLongParameter(request, "documentId");
            final Long catalogId = RequestUtil.getLongParameter(request, "catalogId");
            final String name = RequestUtil.getStringParameter(request, "name");
            final Integer type = RequestUtil.getIntegerParameter(request, "type");
            if (documentId == null || catalogId == null || name == null || type == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("参数不足");
            }
            final String content = RequestUtil.getStringParameter(request, "content");
            final Integer order = RequestUtil.getIntegerParameter(request, "order", 1);

            Assets assets = new Assets();
            assets.setDocumentId(documentId);
            assets.setCatalogId(catalogId);
            assets.setType(AssetsType.valueOf(type));
            assets.setName(name);
            assets.setCreateTime(new Date());
            assets.setCreatorId(getUserID());
            assets.setContent(content);
            assets.setOrder(order);

            Long assetsId = assetsService.insert(assets);
            if (assetsId > 0) {
                return R.ok().message("创建资源成功").put("assetsId", assetsId);
            } else if (assetsId == -2) {
                return R.error().code(ResultCode.ERROR.getCode()).message("该资源已存在，请勿重复添加");
            } else {
                return R.error().code(ResultCode.ERROR.getCode()).message("创建资源失败，请检数据库日志");
            }
        } catch (Exception e) {
            System.out.println(e);
            return R.error().code(ResultCode.ERROR.getCode()).message("创建资源失败 ，请检查系统日志");
        }
    }

    /**
     * @param : 改啥给啥
     * @return : 更新资源
     */
    @Action
    public R updateAssets(HttpServletRequest request) {
        try {
            final Long id = RequestUtil.getLongParameter(request, "id");

            if (id == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("资源id为空");
            }
            final Long documentId = RequestUtil.getLongParameter(request, "documentId");
            final Long catalogId = RequestUtil.getLongParameter(request, "catalogId");
            final String name = RequestUtil.getStringParameter(request, "name");
            final String content = RequestUtil.getStringParameter(request, "content");
            final Integer order = RequestUtil.getIntegerParameter(request, "order");

            Assets assets = new Assets();
            assets.setId(id);
            assets.setDocumentId(documentId);
            assets.setCatalogId(catalogId);
            assets.setName(name);
            assets.setContent(content);
            assets.setOrder(order);

            int updateCount = assetsService.update(assets);
            if (updateCount > 0) {
                return R.ok().message("更新资源成功");
            } else {
                return R.error().code(ResultCode.ERROR.getCode()).message("更新资源失败，没有找到该数据");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("更新资源失败，请检查系统日志");
        }
    }


    /**
     * @param : id
     * @return : 根据资源id删除资源
     */
    @Action
    public R deleteAssetsById(HttpServletRequest request) {
        try {
            final Long id = RequestUtil.getLongParameter(request, "id");
            if (id == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("资源id为空");
            }
            if (assetsService.getById(id) == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("资源不存在，无法删除");
            }
            assetsService.delete(id);
            return R.ok().message("删除资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("删除资源失败，请检查系统日志");
        }
    }


    /**
     * @param : id列表
     * @return : 根据资源id列表批量删除资源
     */
    @Action
    public R deleteManyAssetsById(HttpServletRequest request) {
        try {
            List<Long> ids = RequestUtil.getLongJsonArrayParameterWithoutRepeat(request, "ids");
            if (CollectionUtils.isEmpty(ids)) {
                return R.error().code(ResultCode.ERROR.getCode()).message("文档id为空");
            }

            assetsService.deleteMany(ids);
            return R.ok().message("删除资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("批量删除资源失败，请检查系统日志");
        }
    }

    /**
     * @param : 文档id
     * @return : 根据文档id删除资源
     */
    @Action
    public R deleteAssetsByDocumentId(HttpServletRequest request) {
        try {
            final Long documentId = RequestUtil.getLongParameter(request, "documentId");
            if (documentId == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("文档id为空");
            }
            assetsService.deleteByDocumentId(documentId);
            return R.ok().message("删除资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("删除资源失败，请检查系统日志");
        }
    }


    /**
     * @param : 目录id
     * @return : 根据目录id删除资源
     */
    @Action
    public R deleteAssetsByCatalogId(HttpServletRequest request) {
        try {
            final Long catalogId = RequestUtil.getLongParameter(request, "catalogId");
            if (catalogId == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            assetsService.deleteByCatalogId(catalogId);
            return R.ok().message("删除资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("删除资源失败，请检查系统日志");
        }
    }

    /**
     * @param : 目录id列表
     * @return : 根据目录id列表批量删除资源
     */
    @Action
    public R deleteManyAssetsByCatalogId(HttpServletRequest request) {
        try {
            List<Long> catalogIds = RequestUtil.getLongJsonArrayParameterWithoutRepeat(request, "catalogIds");
            if (CollectionUtils.isEmpty(catalogIds)) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            assetsService.deleteManyByCatalogId(catalogIds);
            return R.ok().message("删除资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("批量删除资源失败，请检查系统日志");
        }
    }

    /**
     * 统计帮区单独目录和文件数据
     *
     * @return
     */
    @Action
    public R getStatisticByCatalogId(HttpServletRequest request) {
        try {
            final Long catalogId = RequestUtil.getLongParameter(request, "catalogId");
            if (catalogId == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("目录id为空");
            }
            HashMap<String, Long> statistic = catalogService.calculateNumberByCatalogId(catalogId);
            return R.ok().put("statistic", statistic).message("获取统计数据成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("根据目录统计数据失败,请检查系统日志");
        }
    }

    /**
     * 统计帮区目录和文件数据
     *
     * @return
     */
    @Action
    public R getStatisticByBandId(HttpServletRequest request) {
        try {
            final Long schoolId = RequestUtil.getLongParameter(request, "schoolId");
            if (schoolId == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("学校id为空");
            }
            HashMap<String, Long> statistic = catalogService.calculateNumberByBandId(getBandObjID(), schoolId);
            return R.ok().put("statistic", statistic).message("获取统计数据成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("获取统计数据失败,请检查系统日志");

        }
    }

    /**
     * 获取全部学校
     *
     * @param request
     * @return
     */

    @Action
    public R getAllSchool(HttpServletRequest request) {
        try {
            final List<School> schools = schoolService.getAllSchool();
            return R.ok().put("schools", schools).message("获取学校成功");
        } catch (Exception e) {
            return R.ok().code(ResultCode.ERROR.getCode()).message("获取学校失败，请检查系统日志");
        }
    }


    /**
     * 获取帮区课程
     *
     * @param request
     * @return
     */
    @Action
    public R getCourseById(HttpServletRequest request) {
        final Long id = RequestUtil.getLongParameter(request, "id");
        try {
            Course byId = courseService.getById(id);
            return R.ok().put("byId", byId).message("获取课程成功");
        } catch (Exception e) {
            return R.ok().code(ResultCode.ERROR.getCode()).message("获取课程失败，请检查系统日志");
        }
    }

    /**
     * 根据学科ID获取课程
     *
     * @param request
     * @return
     */
    @Action
    public R getCourseBySubjectId(HttpServletRequest request) {
        final Long subjectId = RequestUtil.getLongParameter(request, "subjectId");
        try {
            List<Course> courseBySubjectId = courseService.getCourseBySubjectId(subjectId);
            return R.ok().put("courseBySubjectId", courseBySubjectId).message("获取课程成功");
        } catch (Exception e) {
            return R.ok().code(ResultCode.ERROR.getCode()).message("获取课程失败，请检查系统日志");
        }
    }

    /**
     * 更新课程信息
     *
     * @param request
     * @return
     */
    @Action
    public R updateCourse(HttpServletRequest request) {
        final Long bandId = RequestUtil.getLongParameter(request, "bandId");

        if (bandId == null) {
            return R.error().code(ResultCode.ERROR.getCode()).message("帮区id为空");
        }
        final String name = RequestUtil.getStringParameter(request, "name");
        final String description = RequestUtil.getStringParameter(request, "description");
        final String image = RequestUtil.getStringParameter(request, "image");
        final String createTime = RequestUtil.getStringParameter(request, "createTime");
        final Long creatorId = RequestUtil.getLongParameter(request, "creatorId");
        final Integer status = RequestUtil.getIntegerParameter(request, "status");
        final Long subjectId = RequestUtil.getLongParameter(request, "subjectId");

        Course course = new Course();
        course.setBandId(bandId);
        course.setName(name);
        course.setDescription(description);
        course.setImage(image);
        course.setCreateTime(createTime);
        course.setCreatorId(creatorId);
        course.setStatus(status);
        course.setSubjectId(subjectId);

        try {
            courseService.update(course);
            return R.ok().message("更新课程成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("更新课程失败，请检查系统日志");
        }
    }

    /**
     * 根据帮区ID删除课程
     *
     * @param request
     * @return
     */
    @Action
    public R deleteCourseByBandId(HttpServletRequest request) {
        try {
            final Long id = RequestUtil.getLongParameter(request, "id");
            if (id == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("id为空");
            }
            if (courseService.getCourseById(id) == null) {
                return R.error().code(ResultCode.ERROR.getCode()).message("资源不存在，无法删除");
            }
            courseService.deleteByBandId(id);
            return R.ok().message("删除资源成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("删除资源失败，请检查系统日志");
        }
    }

    /**
     * 根据习题ID获取习题
     *
     * @param request
     * @return
     */

    @Action
    public R getHomeworkById(HttpServletRequest request) {
        final Long id = RequestUtil.getLongParameter(request, "id");
        try {
            List<Homework> homeworkById = homeworkService.getHomeworkById(id);
            return R.ok().put("homeworkById", homeworkById).message("获取习题成功");
        } catch (Exception e) {
            return R.ok().code(ResultCode.ERROR.getCode()).message("获取课程失败，请检查系统日志");
        }
    }

    /**
     * 根据用户ID获取学生
     *
     * @param request
     * @return
     */
    @Action
    public R getStudentByUserId(HttpServletRequest request) {
        final Long userId = RequestUtil.getLongParameter(request, "userId");
        try {
            List<Student> studentByUserId = studentService.getStudentByUserId(userId);
            return R.ok().put("studentByUserId", studentByUserId).message("获取学生成功");
        } catch (Exception e) {
            return R.ok().code(ResultCode.ERROR.getCode()).message("获取课程失败，请检查系统日志");
        }
    }

    /**
     * 根据用户ID获取老师
     *
     * @param request
     * @return
     */
    @Action
    public R getTeacherByUserId(HttpServletRequest request) {
        final Long userId = RequestUtil.getLongParameter(request, "userId");
        try {
            List<Teacher> teacherByUserId = teacherService.getTeacherByUserId(userId);
            return R.ok().put("teacherByUserId", teacherByUserId).message("获取教师成功");
        } catch (Exception e) {
            return R.ok().code(ResultCode.ERROR.getCode()).message("获取课程失败，请检查系统日志");
        }
    }

    /**
     * 根据小组ID获取小组
     *
     * @param request
     * @return
     */

    @Action
    public R getTeamByTeamId(HttpServletRequest request) {
        final Long teamId = RequestUtil.getLongParameter(request, "teamId");
        try {
            Team teamByTeamId = teamService.getById(teamId);
            return R.ok().put("teamByTeamId", teamByTeamId).message("获取用户成功");
        } catch (Exception e) {
            return R.ok().code(ResultCode.ERROR.getCode()).message("获取课程失败，请检查系统日志");
        }
    }

    /**
     * 添加习题
     *
     * @param request
     * @return
     */
    @Action
    public R insertHomework(HttpServletRequest request) {
        final Long id = RequestUtil.getLongParameter(request, "id");
        final Long teacherId = RequestUtil.getLongParameter(request, "teacherId");
        final Long catalogId = RequestUtil.getLongParameter(request, "catalogId");
        final Long classId = RequestUtil.getLongParameter(request, "classId");
        final String homeworkName = RequestUtil.getStringParameter(request, "homeworkName");
        final String createTime = RequestUtil.getStringParameter(request, "createTime");
        final Long homeworkSubmitId = RequestUtil.getLongParameter(request, "homeworkSubmitId");
        Homework homework = new Homework();
        homework.setId(id);
        homework.setTeacherId(teacherId);
        homework.setCatalogId(catalogId);
        homework.setClassId(classId);
        homework.setHomeworkName(homeworkName);
        homework.setCreateTime(createTime);
        homework.setHomeworkSubmitId(homeworkSubmitId);
        try {
            homeworkService.insertHomework(homework);
            return R.ok().message("添加习题成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().code(ResultCode.ERROR.getCode()).message("添加习题失败，请检查系统日志");
        }
    }
}